/**
 * Created by ruiyuan on 15-8-11.
 */

var appService = require('../services/appService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var Users = mongoose.model('user');
var async = require('async');
var md5 = require('MD5');
var moment = require('moment');
var marketService = require('../services/marketService');
var userController = require('../controllers/user-controller');

var pinyin = require("pinyin");

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
var userService = require('../services/userService');
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   start   */
var Geetest = require('gt3-sdk');
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   end   */

/**
 * 获取手机号状态
 * @param req
 * @param res
 */
exports.getMobilePhoneStatus = function (req, res) {
    var mobilePhone = req.params.mobilePhone;

    appService.getMobilePhoneStatusService(mobilePhone, function (err, result) {
        if (err) {
            logger.error('Failed to getMobilePhoneStatus ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 2001))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2001))
        }
    })
};

/**
 * 获取短信验证码
 * @param req
 * @param res
 */
exports.getSmsVerificationCode = function (req, res) {
    /*  宝宝树66小区二期拼团    mod  注册极验证 luolh  20170830   start   */
    // res.json(messageUtil.composeFailedMessage(req, 'APP有新版本发布,请更新下载,此版获取短信已失效!', 2001));
   // res.json(messageUtil.composeErrorMessage(req, {status: 0, message: 'APP有新版本发布,请更新下载,此版获取短信已失效!'}, 2002));

    var mobilePhone = req.body.mobilePhone;
    var type = req.body.type;
    // 只能是1,2，4
    if(type == '1' || type == '2' || type == '4') {
        var deviceId = req.params.deviceId;

        var keyA = 'day:' + moment().format('YYYYMMDD') + ':mobile:' + mobilePhone + ':' + type + ':sms:count';

        redisClient.get(keyA, function (err, value) {
            if (Number(value) < 5) {
                    appService.getSmsVerificationCodeService(mobilePhone, type, function (err, result) {
                        if (err) {
                            logger.error('Failed to getSmsVerificationCode---' + err.message);
                            res.json(messageUtil.composeErrorMessage(req, err, 2002))
                        } else {

                            res.json(messageUtil.composeSucceededMessage(req, null, null, 2002));

                            //push到短信发送队列
                            var message = {
                                "deviceId": deviceId,
                                "mobilePhone": mobilePhone,
                                "verificationCode": result,
                                "type": type
                            };
                            toolUtil.putMessageVerificationCodeMQ(message);

                            // 追加频率限制-start
                            redisClient.incr(keyA, function(err, reply) {
                                redisClient.expire(keyA, 86400); // 1天
                            });
                            // 追加频率限制-end

                            if (type == '1' || type == '2') {

                                var clickMessage = {
                                    type: type == '1' ? 45 : 48,
                                    typeDesc: type == '1' ? '短信验证码（注册）' : '短信验证码（忘记密码）',
                                    deviceId: deviceId,
                                    ext: mobilePhone,
                                    vname: req.query.vname,
                                    vcode: req.query.vcode,
                                    os: req.query.type,
                                    createTime: new Date().getTime()
                                };
                                toolUtil.putMessageLogMQ(clickMessage);
                            }
                        }
                    });
            } else {
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '发送失败，当天短信数量超出限制'}, 2002));
            }
        });
    } else {
        logger.debug("修改密码使用type错误...");
        res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '非法操作'}, 2002))
    }
    /*  宝宝树66小区二期拼团    mod  注册极验证 luolh  20170830   start   */
};

/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170829   start   */
/**
 * 获取短信验证码
 * @param req
 * @param res
 */
exports.getSmsVerificationCodeGeetest = function (req, res) {
    redisClient.get('captchRegister:getSmsValidate:'+req.params.deviceId, function (err, value) {
        if (err || value == null || value == "false") {
            res.json(messageUtil.composeErrorMessage(req, {status:0,message:"非法操作"}, 2002))
        } else {
            var mobilePhone = req.body.mobilePhone;
            var type = req.body.type;
            var deviceId = req.params.deviceId;

            var type = req.body.type;
            // 修改密码只能是4
            if(type == '1' || type == '2' || type == '4') {
                var keyA = 'day:' + moment().format('YYYYMMDD') + ':mobile:' + mobilePhone + ':' + type + ':sms:count';

                redisClient.get(keyA, function (err, value) {
                    if (Number(value) < 5) {
                        appService.getSmsVerificationCodeService(mobilePhone, type, function (err, result) {
                            if (err) {
                                logger.error('Failed to getSmsVerificationCode---' + err.message);
                                res.json(messageUtil.composeErrorMessage(req, err, 2002))
                            } else {

                                res.json(messageUtil.composeSucceededMessage(req, null, null, 2002));

                                //push到短信发送队列
                                var message = {
                                    "deviceId": deviceId,
                                    "mobilePhone": mobilePhone,
                                    "verificationCode": result,
                                    "type": type
                                };
                                toolUtil.putMessageVerificationCodeMQ(message);

                                // 追加频率限制-start
                                redisClient.incr(keyA, function(err, reply) {
                                    redisClient.expire(keyA, 86400); // 1天
                                });
                                // 追加频率限制-end

                                if (type == '1' || type == '2') {

                                    var clickMessage = {
                                        type: type == '1' ? 45 : 48,
                                        typeDesc: type == '1' ? '短信验证码（注册）' : '短信验证码（忘记密码）',
                                        deviceId: deviceId,
                                        ext: mobilePhone,
                                        vname: req.query.vname,
                                        vcode: req.query.vcode,
                                        os: req.query.type,
                                        createTime: new Date().getTime()
                                    };

                                    toolUtil.putMessageLogMQ(clickMessage);
                                }
                                redisClient.set('captchRegister:getSmsValidate:'+req.params.deviceId, false);

                                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
                                redisClient.set('captchRegister:nextFlag:' + req.params.deviceId, true);
                                redisClient.EXPIRE('captchRegister:nextFlag:' + req.params.deviceId, 86400);
                                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */
                            }
                        });
                    } else {
                        res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '发送失败，当天短信数量超出限制'}, 2002));
                    }
                });
            } else {
                logger.debug("getSmsVerificationCodeGeetest使用type错误...");
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '非法操作'}, 2002))
            }
        }
    });

};
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170829   end   */

/**
 * 获取语音验证码
 * @param req
 * @param res
 */
exports.getVoiceVerificationCode = function (req, res) {

    var mobilePhone = req.body.mobilePhone;
    var type = req.body.type;
    var deviceId = req.params.deviceId;

    appService.getVoiceVerificationCodeService(mobilePhone, type, function (err, result) {
        if (err) {
            logger.error('Failed to getVoiceVerificationCode---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2003))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 2003));

            if (type == '1' || type == '2') {

                var clickMessage = {
                    type: type == '1' ? 46 : 49,
                    typeDesc: type == '1' ? '语音验证码（注册）' : '语音验证码（忘记密码）',
                    deviceId: deviceId,
                    ext: mobilePhone,
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(clickMessage);
            }
        }
    })
};

/**
 * 重置密码
 * @param req
 * @param res
 */
exports.resetPassword = function (req, res) {

    if(toolUtil.isNowBiggerThanOldGeetestEndDate()) {
        res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
    } else {
        var clientIp = toolUtil.getClientIp(req); // 用户IP地址

        /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
        redisClient.get('captchRegister:nextFlag:' + req.params.deviceId, function (err, value) {
            if (err || value == null || value == "false") {
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: "请前往应用宝下载最新版本!"}, 2004));
            } else {
                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */
                var mobilePhone = req.body.mobilePhone;
                var code = req.body.code;
                var type = req.body.type;
                var userPassword = req.body.userPassword;

                appService.resetPasswordService(mobilePhone, type, code, userPassword, clientIp, function (err, result) { // 新
                    // appService.resetPasswordService(mobilePhone, type, code, userPassword, function (err, result) { // 旧
                    if (err) {
                        logger.error('Failed to resetPassword---' + err.message);
                        res.json(messageUtil.composeErrorMessage(req, err, 2004))
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 2004));

                        var clickMessage = {
                            type: 50,
                            typeDesc: '忘记密码',
                            deviceId: req.params.deviceId,
                            vname: req.query.vname,
                            vcode: req.query.vcode,
                            os: req.query.type,
                            createTime: new Date().getTime()
                        };
                        toolUtil.putMessageLogMQ(clickMessage);

                        /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
                        redisClient.set('captchRegister:nextFlag:' + req.params.deviceId, false);
                        /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */

                    }
                })
            }
        });
    }
};

/**
 * 校验验证码
 * @param req
 * @param res
 */
exports.checkVerificationCode = function (req, res) {
    var mobilePhone = req.body.mobilePhone;
    var type = req.body.type;
    var code = req.body.code;

    appService.checkVerificationCodeService(mobilePhone, type, code, function (err, result) {
        if (err) {
            logger.error('Failed to checkVerificationCode---' + err.message);
            var lang = req.cparams.lang;

            console.log("lang: ", lang);

            var errorMsg = 'Invalid Verification Code.';
            if (!lang)
                errorMsg = '验证码错误';

            res.json(messageUtil.composeErrorMessage(req, {status: 0, message: errorMsg}, 2005))
        } else {
            /* 宝宝树66小区二期拼团    mod 取消手机注册验证  llh  20170822   start */

            // /*  宝宝树66小区二次改造    add   llh  20170717   start   */
            // appService.getBabyTreeRegisterUserInfoService(mobilePhone, function (err, result) {
            //     if (err) {
            //         logger.error('Failed to checkVerificationCode---' + err.message);
            //         var lang = req.cparams.lang;
            //
            //         console.log("lang: ", lang);
            //
            //         var errorMsg = 'Invalid Verification Code.';
            //         if (!lang)
            //             errorMsg = '千里眼小六看宝宝树遇阻';
            //
            //         res.json(messageUtil.composeErrorMessage(req, {status: 0, message: errorMsg}, 2005))
            //     } else {
            //         var resJson = {};
            //         // TODO luolh
            //         logger.info(typeof(result));
            //         // resJson = JSON.parse(result);
            //         res.json(messageUtil.composeSucceededMessage(req, null, result, 2005))
            //     }
            // });
            // // res.json(messageUtil.composeSucceededMessage(req, null, null, 2005))
            // /*  宝宝树66小区二次改造    add   llh  20170717   end   */
            var data = {
                data: null,
                status: "non_register",
                message: "该手机号还未注册"
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 2005));
            /* 宝宝树66小区二期拼团    mod 短信两次修正  llh  20170822   end */
        }
    })
};
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   start   */

/**
 * 初始化
 * @param req
 * @param res
 */
exports.captchRegister = function (req, res) {
    var clientType = req.body.clientType;
    var data = {
        client_type : 'h5',
        native :'unknown',
        ip_address:'unknnow'
    };
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });
    captcha.register(data, function (err, data) {
        if (err) {
            console.error(err);
            return;
        }
        if (!data.success) {
            // 进入 fallback，如果一直进入此模式，请检查服务器到极验服务器是否可访问
            // 可以通过修改 hosts 把极验服务器 api.geetest.com 指到不可访问的地址
            // 为以防万一，你可以选择以下两种方式之一：
            // 1. 继续使用极验提供的failback备用方案
            req.session.fallback = true;
            logger.debug("fallback:true"+req.session.id);
            redisClient.set('captchRegister:fallback:'+req.session.id, true);
            redisClient.EXPIRE('captchRegister:value', 86400);
            res.send(data);
            // 2. 使用自己提供的备用方案
            // todo
        } else {
            // 正常模式
            logger.debug("fallback:false"+req.session.id);
            redisClient.set('captchRegister:fallback:'+req.session.id, false);
            redisClient.EXPIRE('captchRegister:value', 86400);
            req.session.fallback = false;
            res.send(data);
        }
    });
};

/**
 * 二次验证
 * @param req
 * @param res
 */
exports.captchValidate = function (req, res) {
    if(toolUtil.isNowBiggerThanOldGeetestEndDate()) {
        res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
    } else {
        appService.captchValidateService(req, function(err, result){
            if (err) {
                res.json(messageUtil.composeFailedMessage(req, "Invalid validate"));
            } else {
                // session中写入发送短信值
                res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
            }
        });
    }
};
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   end   */


/*  宝宝树66小区二期拼团    add  登陆极验证 guo.xiaomin  20170919   start   */
/**
 * 二次验证
 * @param req
 * @param res
 */
exports.captchValidateLogin = function (req, res) {
    if(toolUtil.isNowBiggerThanOldGeetestEndDate()) {
        res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
    } else {
        appService.captchValidateLoginService(req, function (err, result) {
            if (err) {
                res.json(messageUtil.composeFailedMessage(req, "captchValidateLoginService Invalid validate"));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
            }
        });
    }
};
/*  宝宝树66小区二期拼团    add  登陆极验证 guo.xiaomin  20170919   end   */

/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   start   */
// 1120-commit-master
// 注册,登陆，忘记密码一次验证
exports.captchRegisterNew = function (req, res) {
    var mobilePhone = req.params.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID
    logger.debug("captchRegisterNew:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    var data = {
        client_type : 'h5',
        native :'unknown',
        ip_address:'unknnow'
    };
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });
    captcha.register(data, function (err, data) {
        if (err) {
            console.error(err);
            return;
        }
        if (!data.success) {
            // 进入 fallback，如果一直进入此模式，请检查服务器到极验服务器是否可访问
            // 可以通过修改 hosts 把极验服务器 api.geetest.com 指到不可访问的地址
            // 为以防万一，你可以选择以下两种方式之一：
            // 1. 继续使用极验提供的failback备用方案
            req.session.fallback = true;
            logger.debug("fallback:true" + deviceId);
            redisClient.setex('captchRegister:fallback:' + mobilePhone + ":" + deviceId, 86400, true);
            res.send(data);
            // 2. 使用自己提供的备用方案
            // todo
        } else {
            // 正常模式
            logger.debug("fallback:false"+req.session.id);
            redisClient.setex('captchRegister:fallback:' + mobilePhone + ":" + deviceId, 86400, false);
            req.session.fallback = false;
            res.send(data);
        }
    });
};

// 注册,忘记密码,二次验证
exports.captchValidateNew = function (req, res) {
    appService.captchValidateNewService(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "Invalid validate"));
        } else {
            // session中写入发送短信值
            res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
        }
    });
};


/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   start   */
// 注册二次验证+取得手机号是否注册
exports.captchValidateRegisterNew = function (req, res) {
    appService.captchValidateRegisterNewService(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "Invalid validate"));
        } else {
            // session中写入发送短信值
            // result = {isRegister: result != null}
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2005));
        }
    });
};
/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   end   */

// 登陆二次验证
exports.captchValidateLoginNew = function (req, res) {
    appService.captchValidateLoginNewService(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "captchValidateLoginService Invalid validate"));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
        }
    });
};

/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   start   */
// 登陆二次验证
exports.captchValidateAppLoginNew = function (req, res) {
    appService.captchValidateLoginNewService(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "captchValidateLoginService Invalid validate"));
        } else {
            if(result) {
                var mobilePhone = req.params.mobilePhone;
                var password = req.params.password;
                var vCode = req.cparams.vcode;
                var lang = req.cparams.lang;
                var vName = req.query.vname; // 版本号

                logger.debug('Trying to login with ' + mobilePhone);

                var clientIp = toolUtil.getClientIp(req); // 用户IP地址

                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   start   */
                userController.checkServiceAccount(mobilePhone, password, function (err, data) {
                    logger.debug("userController.checkServiceAccount success...");
                    var isServiceAccount = data.isServiceAccount;
                    if(isServiceAccount) {
                        var user = data.user;
                        // 登陆失败
                        if(user == null) {
                            var message = {
                                "deviceId": req.params.deviceId,
                                "mobilePhone": mobilePhone,
                                "password": password,
                                "message": "invalid loginID or password"
                            };

                            var errorMsg = 'Invalid Account or Password.';
                            if (!lang)
                            /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                            // errorMsg = '用户名或密码错误'; // 旧
                                errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                            /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                            logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                            res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                            toolUtil.putMessageLoginOrRegisterLogMQ(message);
                        } else {
                            // 登陆成功
                            var resultData = user;
                            var token = toolUtil.getUserTokenById(user._id);
                            resultData['token'] = token;
                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                            // if (results[7] == null || newProtocolVersion != results[7])
                            userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                                if (err) {
                                    logger.error("更新最新用户协议版本号出错");
                                } else {
                                    logger.info("更新最新用户协议版本号成功");
                                }
                            });
                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */
                            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', resultData, 1002));
                            toolUtil.setUserByToken(token, true);
                        }
                    } else { // 不是小6客服账号
                        /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   start   */
                        // userService.appLoginService(deviceId, channelId, mobilePhone, password, null, vCode, function (err, results) {
                        userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, clientIp, function (err, results) { // 新
                            // userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, function (err, results) { // 旧
                            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   end   */
                            if (err) {

                                var message = {
                                    "deviceId": req.params.deviceId,
                                    "mobilePhone": mobilePhone,
                                    "password": password,
                                    "message": err.message
                                };
                                logger.error(mobilePhone + 'Exception happened when login to the system...!-' + err.message);
                                // res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message, 1002));
                                res.json(messageUtil.composeFailedMessage(req, err.message, 1002));
                                toolUtil.putMessageLoginOrRegisterLogMQ(message);
                            } else {
                                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                                // 0,1,2,3,4,5->添加[a],0,[b],1,2,3,4,5->[a]0,[0]1,[b]2,[1]3,[2]4,[3]5,[4]6,[5]7
                                //只要结果集中有一个返回值，则表明有记录，说明用户合法
                                //if (results[0] != null) {
                                if (results[1] != null) {
                                    //if (results[0].frozenOrNot) {
                                    if (results[1].frozenOrNot) {
                                        var errorMsg = 'Account Frozen';
                                        if (!lang)
                                            errorMsg = '帐号被冻结';

                                        res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                                    } else {
                                        var _id = results[1]._id;
                                        // var _id = results[0]._id;
                                        logger.debug(mobilePhone + ' Logined into the system successfully...!');
                                        //获取token并缓冲
                                        var token = toolUtil.getUserTokenById(_id);
                                        // var data = results[0];
                                        var data = results[1];
                                        data.frozenOrNot = undefined;
                                        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                                        if (results[0]) {
                                            // 宝宝树直接登录
                                            data._doc['loginStr'] = results[0].loginStr;
                                            data._doc['meitunToken'] = results[0].token;
                                        } else {
                                            // 老用户注册后登录
                                            data._doc['loginStr'] = results[2].loginStr;
                                            data._doc['meitunToken'] = results[2].token;
                                        }
                                        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */


                                        data._doc['token'] = token;
                                        data._doc['auth'] = results[3];
                                        data._doc['vStatus'] = results[4];
                                        data._doc['isSignIn'] = results[5];
                                        data._doc['taskFlag'] = results[7];
                                        // data._doc['auth'] = results[1];
                                        // data._doc['vStatus'] = results[2];
                                        // data._doc['isSignIn'] = results[3];
                                        // data._doc['taskFlag'] = results[5];

                                        //if (results[4] != null) {
                                        if (results[6] != null) {
                                            data._doc['communityApply'] = results[6];
                                            // data._doc['communityApply'] = results[4];
                                        }

                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                                        // if (results[7] == null || newProtocolVersion != results[7])
                                        userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                                            if (err) {
                                                logger.error("更新最新用户协议版本号出错");
                                            } else {
                                                logger.info("更新最新用户协议版本号成功");
                                            }
                                        });
                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */

                                        res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data, 1002));
                                        toolUtil.setUserByToken(token, true);
                                    }
                                } else {
                                    var message = {
                                        "deviceId": req.params.deviceId,
                                        "mobilePhone": mobilePhone,
                                        "password": password,
                                        "message": "invalid loginID or password"
                                    };

                                    var errorMsg = 'Invalid Account or Password.';
                                    if (!lang)
                                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                                    // errorMsg = '用户名或密码错误'; // 旧
                                        errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                                    logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                                    res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                                    toolUtil.putMessageLoginOrRegisterLogMQ(message);
                                }
                            }
                        })
                    }
                });

                // res.json(messageUtil.composeSucceededMessage(req, null, returnData, 2005))
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
            }
        }
    });
};
/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   end   */

/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171212   start   */
// 登陆二次验证
exports.captchValidateAppLoginFinal = function (req, res) {
    appService.captchValidateLoginNewService(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "captchValidateLoginService Invalid validate"));
        } else {
            if(result) {
                var mobilePhone = req.params.mobilePhone;
                // var password = req.params.password;
                var password = req.body.password;
                var vCode = req.cparams.vcode;
                var lang = req.cparams.lang;
                var vName = req.query.vname; // 版本号

                logger.debug('Trying to login with ' + mobilePhone);

                var clientIp = toolUtil.getClientIp(req); // 用户IP地址

                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   start   */
                userController.checkServiceAccount(mobilePhone, password, function (err, data) {
                    logger.debug("userController.checkServiceAccount success...");
                    var isServiceAccount = data.isServiceAccount;
                    if(isServiceAccount) {
                        var user = data.user;
                        // 登陆失败
                        if(user == null) {
                            var message = {
                                "deviceId": req.params.deviceId,
                                "mobilePhone": mobilePhone,
                                "password": password,
                                "message": "invalid loginID or password"
                            };

                            var errorMsg = 'Invalid Account or Password.';
                            if (!lang)
                            /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                            // errorMsg = '用户名或密码错误'; // 旧
                                errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                            /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                            logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                            res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                            toolUtil.putMessageLoginOrRegisterLogMQ(message);
                        } else {
                            // 登陆成功
                            var resultData = user;
                            var token = toolUtil.getUserTokenById(user._id);
                            resultData['token'] = token;
                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                            // if (results[7] == null || newProtocolVersion != results[7])
                            userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                                if (err) {
                                    logger.error("更新最新用户协议版本号出错");
                                } else {
                                    logger.info("更新最新用户协议版本号成功");
                                }
                            });
                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */
                            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', resultData, 1002));
                            toolUtil.setUserByToken(token, true);
                        }
                    } else { // 不是小6客服账号
                        /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   start   */
                        // userService.appLoginService(deviceId, channelId, mobilePhone, password, null, vCode, function (err, results) {
                        userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, clientIp, function (err, results) { // 新
                            // userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, function (err, results) { // 旧
                            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   end   */
                            if (err) {

                                var message = {
                                    "deviceId": req.params.deviceId,
                                    "mobilePhone": mobilePhone,
                                    "password": password,
                                    "message": err.message
                                };
                                logger.error(mobilePhone + 'Exception happened when login to the system...!-' + err.message);
                                // res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message, 1002));
                                res.json(messageUtil.composeFailedMessage(req, err.message, 1002));
                                toolUtil.putMessageLoginOrRegisterLogMQ(message);
                            } else {
                                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                                // 0,1,2,3,4,5->添加[a],0,[b],1,2,3,4,5->[a]0,[0]1,[b]2,[1]3,[2]4,[3]5,[4]6,[5]7
                                //只要结果集中有一个返回值，则表明有记录，说明用户合法
                                //if (results[0] != null) {
                                if (results[1] != null) {
                                    //if (results[0].frozenOrNot) {
                                    if (results[1].frozenOrNot) {
                                        var errorMsg = 'Account Frozen';
                                        if (!lang)
                                            errorMsg = '帐号被冻结';

                                        res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                                    } else {
                                        var _id = results[1]._id;
                                        // var _id = results[0]._id;
                                        logger.debug(mobilePhone + ' Logined into the system successfully...!');
                                        //获取token并缓冲
                                        var token = toolUtil.getUserTokenById(_id);
                                        // var data = results[0];
                                        var data = results[1];
                                        data.frozenOrNot = undefined;
                                        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                                        if (results[0]) {
                                            // 宝宝树直接登录
                                            data._doc['loginStr'] = results[0].loginStr;
                                            data._doc['meitunToken'] = results[0].token;
                                        } else {
                                            // 老用户注册后登录
                                            data._doc['loginStr'] = results[2].loginStr;
                                            data._doc['meitunToken'] = results[2].token;
                                        }
                                        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */


                                        data._doc['token'] = token;
                                        data._doc['auth'] = results[3];
                                        data._doc['vStatus'] = results[4];
                                        data._doc['isSignIn'] = results[5];
                                        data._doc['taskFlag'] = results[7];
                                        // data._doc['auth'] = results[1];
                                        // data._doc['vStatus'] = results[2];
                                        // data._doc['isSignIn'] = results[3];
                                        // data._doc['taskFlag'] = results[5];

                                        //if (results[4] != null) {
                                        if (results[6] != null) {
                                            data._doc['communityApply'] = results[6];
                                            // data._doc['communityApply'] = results[4];
                                        }

                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                                        // if (results[7] == null || newProtocolVersion != results[7])
                                        userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                                            if (err) {
                                                logger.error("更新最新用户协议版本号出错");
                                            } else {
                                                logger.info("更新最新用户协议版本号成功");
                                            }
                                        });
                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */

                                        res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data, 1002));
                                        toolUtil.setUserByToken(token, true);
                                    }
                                } else {
                                    var message = {
                                        "deviceId": req.params.deviceId,
                                        "mobilePhone": mobilePhone,
                                        "password": password,
                                        "message": "invalid loginID or password"
                                    };

                                    var errorMsg = 'Invalid Account or Password.';
                                    if (!lang)
                                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                                    // errorMsg = '用户名或密码错误'; // 旧
                                        errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                                    logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                                    res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                                    toolUtil.putMessageLoginOrRegisterLogMQ(message);
                                }
                            }
                        })
                    }
                });

                // res.json(messageUtil.composeSucceededMessage(req, null, returnData, 2005))
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
            }
        }
    });
};
/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171212   end   */

// 获取验证码
exports.getSmsVerificationCodeGeetestNew = function (req, res) {

    var mobilePhone = req.body.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID

    logger.debug("getSmsVerificationCodeGeetestNew:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    redisClient.get('captchRegister:getSmsValidate:' + mobilePhone + ":" + deviceId, function (err, value) {
        if (err || value == null || value == "false") {
            logger.debug("captchRegister:getSmsValidate:false getSmsVerificationCodeGeetestNew...");
            res.json(messageUtil.composeErrorMessage(req, {status:0,message:"非法操作"}, 2002))
        } else {
            // var mobilePhone = req.body.mobilePhone;
            var type = req.body.type;
            // 修改密码只能是4
            if(type == '1' || type == '2' ) {
                var keyA = 'day:' + moment().format('YYYYMMDD') + ':mobile:' + mobilePhone + ':' + type + ':sms:count';

                redisClient.get(keyA, function (err, value) {
                    if (Number(value) < 5) {
                        appService.getSmsVerificationCodeService(mobilePhone, type, function (err, result) {
                            if (err) {
                                logger.error('Failed to getSmsVerificationCode---' + err.message);
                                res.json(messageUtil.composeErrorMessage(req, err, 2002))
                            } else {

                                res.json(messageUtil.composeSucceededMessage(req, null, null, 2002));

                                //push到短信发送队列
                                var message = {
                                    "deviceId": deviceId,
                                    "mobilePhone": mobilePhone,
                                    "verificationCode": result,
                                    "type": type
                                };
                                toolUtil.putMessageVerificationCodeMQ(message);

                                // 追加频率限制-start
                                redisClient.incr(keyA, function(err, reply) {
                                    redisClient.expire(keyA, 86400); // 1天
                                });
                                // 追加频率限制-end

                                if (type == '1' || type == '2') {

                                    var clickMessage = {
                                        type: type == '1' ? 45 : 48,
                                        typeDesc: type == '1' ? '短信验证码（注册）' : '短信验证码（忘记密码）',
                                        deviceId: deviceId,
                                        ext: mobilePhone,
                                        vname: req.query.vname,
                                        vcode: req.query.vcode,
                                        os: req.query.type,
                                        createTime: new Date().getTime()
                                    };

                                    toolUtil.putMessageLogMQ(clickMessage);
                                }
                                // 重新发送可以点击
                                // redisClient.setex('captchRegister:getSmsValidate:'+ mobilePhone + ":" + deviceId, 86400, false);
                                redisClient.setex('captchRegister:nextFlag:' + mobilePhone + ":" + deviceId, 86400, true);
                            }
                        });
                    } else {
                        res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '发送失败，当天短信数量超出限制'}, 2002));
                    }
                });
            } else {
                logger.debug("注册或者忘记密码使用type错误...");
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '非法操作'}, 2002))
            }
        }
    });

};

// 重置密码
exports.resetPasswordNew = function (req, res) {

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址
    var mobilePhone = req.body.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID

    logger.debug("resetPasswordNew:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
    redisClient.get('captchRegister:nextFlag:' + mobilePhone + ":" + deviceId, function (err, value) {
        if (err || value == null || value == "false") {
            res.json(messageUtil.composeErrorMessage(req, {status:0, message:"请前往应用宝下载最新版本!"}, 2004));
        } else {
            /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */
            var code = req.body.code;
            var type = req.body.type;
            var userPassword = req.body.userPassword;

            appService.resetPasswordService(mobilePhone, type, code, userPassword, clientIp, function (err, result) {
                if (err) {
                    logger.error('Failed to resetPassword---' + err.message);
                    res.json(messageUtil.composeErrorMessage(req, err, 2004))
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null, 2004));

                    var clickMessage = {
                        type: 50,
                        typeDesc: '忘记密码',
                        deviceId: req.params.deviceId,
                        vname: req.query.vname,
                        vcode: req.query.vcode,
                        os: req.query.type,
                        createTime: new Date().getTime()
                    };
                    toolUtil.putMessageLogMQ(clickMessage);

                    redisClient.setex('captchRegister:nextFlag:' + mobilePhone + ":" + deviceId, 86400, false);

                }
            })
        }});
};

// 注册
exports.signUpNew = function (req, res) {

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址
    var mobilePhone = req.body.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID

    logger.debug("signUpNew:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    redisClient.get('captchRegister:nextFlag:' + mobilePhone + ":" +deviceId, function (err, value) {
        if (err || value == null || value == "false") {
            res.json(messageUtil.composeErrorMessage(req, {status:0, message:"请前往应用宝下载最新版本!"}, 2002))
        } else {
            var input = req.body;
            var code = req.body.code;
            var verKey = 'ver:code:' + mobilePhone + ':1'; // 注册
            var errorKey = verKey + ":errorCount";

            redisClient.get(errorKey, function(err, getReply) {
                if (getReply != null && getReply >= 3) {
                    logger.debug("验证码错误次数太多，锁定1小时!..." + errorKey);
                    res.json(messageUtil.composeErrorMessage(req, {status:0, message:"验证码错误次数太多，锁定1小时!"}, 2002))
                } else {
                    redisClient.get(verKey, function (err, value) {
                        if (value != null && value == code) {
                            // 正常注册
                            if (req.query.channelId)
                                input.channelId = req.query.channelId;

                            var key = 'app:user:device:register';

                            input.deviceId = deviceId;
                            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170826   start */
                            input.type = req.query.type;
                            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170826  end */
                            redisClient.HGET(key, deviceId, function (err, value) {

                                if (value == null || (value != null && value.split(',').length < REGISTER_LIMIT)) {
                                    appService.signUpService(input, clientIp, function (err, result) { // 新
                                        // appService.signUpService(input, function (err, result) { // 旧
                                        if (err) {
                                            logger.error('Failed to signUp ---' + err);
                                            logger.error('Failed to signUp ---' + err.message);

                                            if (lang && lang == 'en_US' && err.message_en_US) {
                                                err.message = err.message_en_US
                                            }
                                            res.json(messageUtil.composeErrorMessage(req, err, 2006))
                                        } else {
                                            result[2]._doc['taskFlag'] = true;
                                            res.json(messageUtil.composeSucceededMessage(req, null, result[2], 2006));

                                            //储存设置注册信息
                                            redisClient.HSET(key, deviceId, value == null ? result[2]._id + '' : value + ',' + result[2]._id);
                                            //第三方注册头像上传
                                            if (input.image != null && input.image != '') {
                                                toolUtil.putMessageThirdPartyImageMQ({user: result[2]._id, image: input.image});
                                            }

                                            //邀请分享记录查询保存
                                            appService.saveUserInvitationRecordService(result[2]._id, input.mobilePhone, deviceId);

                                            if (Number(req.query.vcode) >= 200000) {
                                                //创建新手任务
                                                appService.createNoviceTaskService(result[2]._id);
                                            }
                                            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */
                                            var clickMessage = {
                                                type: input.thirdParty ? 53 : 47,
                                                typeDesc: input.thirdParty ? '第三方设置密码昵称' : '设置密码、昵称',
                                                deviceId: deviceId,
                                                vname: req.query.vname,
                                                vcode: req.query.vcode,
                                                os: req.query.type,
                                                createTime: new Date().getTime()
                                            };
                                            toolUtil.putMessageLogMQ(clickMessage);

                                            redisClient.setex('captchRegister:nextFlag:' + mobilePhone + ":" + deviceId, 86400, false);

                                        }
                                    });
                                } else {
                                    var lang = req.cparams.lang;

                                    var errorMsg = 'You have reached account limit.';
                                    if (!lang)
                                        errorMsg = '手机注册达到上限';

                                    res.json(messageUtil.composeFailedMessage(req, errorMsg, 2006))
                                }
                            });
                        } else {
                            redisClient.incr(errorKey, function(err, reply) {
                                redisClient.expire(errorKey, 3600); // 1小时
                                logger.debug("验证码错误..." + errorKey);

                                var lang = req.cparams.lang;
                                // 异常注册
                                var errorMsg = 'invalid signUp.';
                                if (!lang)
                                    errorMsg = '异常注册.';
                                res.json(messageUtil.composeFailedMessage(req, errorMsg, 2006))
                            });
                        }
                    });
                }
            });
        }
    });
};
/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   end   */

/**
 * 注册 （设置密码和昵称）
 * @param req
 * @param res
 */
exports.signUp = function (req, res) {

    if(toolUtil.isNowBiggerThanOldGeetestEndDate()) {
        res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
    } else {
        var clientIp = toolUtil.getClientIp(req); // 用户IP地址

        /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
        redisClient.get('captchRegister:nextFlag:' + req.params.deviceId, function (err, value) {
            if (err || value == null || value == "false") {
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: "请前往应用宝下载最新版本!"}, 2002))
            } else {
                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */

                var input = req.body;

                /*  宝宝树66小区四次改造 任意手机号注册安全问题   mod   guo.xiaomin  20171024   start   */
                // TODO 需要客户端传递验证码到后台，才可以放开当前注释
                // var mobilePhone = input.mobilePhone; // 手机号
                var code = req.body.code; // 验证码(当前版本没有传递)
                logger.debug("code..." + code);
                // var verKey = 'ver:code:' + mobilePhone + ':1'; // 注册
                // redisClient.get(key, function (err, value) {
                //     if (value != null && value == code) {
                //         // 正常注册
                //
                //     } else {
                //         // 异常注册
                //         var errorMsg = 'invalid signUp.';
                //         if (!lang)
                //             errorMsg = '异常注册.';
                //
                //         res.json(messageUtil.composeFailedMessage(req, errorMsg, 2006))
                //     }
                // });
                /*  宝宝树66小区四次改造 任意手机号注册安全问题   mod   guo.xiaomin  20171024   end   */

                var deviceId = req.params.deviceId;

                if (req.query.channelId)
                    input.channelId = req.query.channelId;

                var key = 'app:user:device:register';

                input.deviceId = deviceId;
                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170826   start */
                input.type = req.query.type;
                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170826  end */
                redisClient.HGET(key, deviceId, function (err, value) {

                    if (value == null || (value != null && value.split(',').length < REGISTER_LIMIT)) {
                        appService.signUpService(input, clientIp, function (err, result) { // 新
                            // appService.signUpService(input, function (err, result) { // 旧
                            if (err) {
                                logger.error('Failed to signUp ---' + err);
                                logger.error('Failed to signUp ---' + err.message);

                                if (lang && lang == 'en_US' && err.message_en_US) {
                                    err.message = err.message_en_US
                                }
                                res.json(messageUtil.composeErrorMessage(req, err, 2006))
                            } else {
                                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                                /*  宝宝树66小区二次改造    add   luolh  20170722   start   */
                                // result[1]._doc['taskFlag'] = true;
                                result[2]._doc['taskFlag'] = true;
                                /*  宝宝树66小区二次改造    add   luolh  20170722   end   */
                                //if (result[3] != null) {
                                //    result[1]._doc['groupInvite'] = result[3];
                                //}
                                /*  宝宝树66小区二次改造    add   luolh  20170722   start   */
                                // res.json(messageUtil.composeSucceededMessage(req, null, result[1], 2006));
                                res.json(messageUtil.composeSucceededMessage(req, null, result[2], 2006));
                                /*  宝宝树66小区二次改造    add   luolh  20170722   end   */

                                //储存设置注册信息
                                /*  宝宝树66小区二次改造    add   luolh  20170722   start   */
                                // redisClient.HSET(key, deviceId, value == null ? result[1]._id + '' : value + ',' + result[1]._id);
                                redisClient.HSET(key, deviceId, value == null ? result[2]._id + '' : value + ',' + result[2]._id);
                                /*  宝宝树66小区二次改造    add   luolh  20170722   end   */
                                //第三方注册头像上传
                                if (input.image != null && input.image != '') {
                                    /*  宝宝树66小区二次改造    add   luolh  20170722   start   */
                                    // toolUtil.putMessageThirdPartyImageMQ({user: result[1]._id, image: input.image})
                                    toolUtil.putMessageThirdPartyImageMQ({user: result[2]._id, image: input.image});
                                    /*  宝宝树66小区二次改造    add   luolh  20170722   end   */
                                }

                                //邀请分享记录查询保存
                                appService.saveUserInvitationRecordService(result[2]._id, input.mobilePhone, deviceId);

                                if (Number(req.query.vcode) >= 200000) {
                                    //创建新手任务
                                    /*  宝宝树66小区二次改造    add   luolh  20170722   end   */
                                    // appService.createNoviceTaskService(result[1]._id);
                                    appService.createNoviceTaskService(result[2]._id);
                                    /*  宝宝树66小区二次改造    add   luolh  20170722   end   */
                                }
                                /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */
                                var clickMessage = {
                                    type: input.thirdParty ? 53 : 47,
                                    typeDesc: input.thirdParty ? '第三方设置密码昵称' : '设置密码、昵称',
                                    deviceId: deviceId,
                                    vname: req.query.vname,
                                    vcode: req.query.vcode,
                                    os: req.query.type,
                                    createTime: new Date().getTime()
                                };
                                toolUtil.putMessageLogMQ(clickMessage);

                                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   start  */
                                redisClient.set('captchRegister:nextFlag:' + req.params.deviceId, false);
                                /*  宝宝树66小区二期拼团    mod  防止暴力注册 guo.xiaomin  20170920   end  */

                            }
                        });
                    } else {
                        var lang = req.cparams.lang;

                        var errorMsg = 'You have reached account limit.';
                        if (!lang)
                            errorMsg = '手机注册达到上限';

                        res.json(messageUtil.composeFailedMessage(req, errorMsg, 2006))
                    }
                });
            }
        });
    }
};

/*  宝宝树66小区二次改造    add   llh  20170717   start   */
/**
 * 注册时取得已经在宝宝树注册的注册信息 （昵称和userId）
 * @param req
 * @param res
 */
exports.babyTreeRegisterUserInfo = function (req, res) {
    var mobilePhone = req.body.mobilePhone;
    var type = req.body.type;
    var code = req.body.code;

    appService.getBabyTreeRegisterUserInfoService(mobilePhone, function (err, result) {
        if (err) {
            logger.error('Failed to checkVerificationCode---' + err.message);
            var lang = req.cparams.lang;

            console.log("lang: ", lang);

            var errorMsg = 'Invalid Verification Code.';
            if (!lang)
                errorMsg = '千里眼小六看宝宝树遇阻';
            res.json(messageUtil.composeErrorMessage(req, {status: 0, message: errorMsg}, 2005))
        } else {
            var resJson = JSON.parse(result);
            res.json(messageUtil.composeSucceededMessage(req, null, resJson, 2005))
        }
    })

};
/*  宝宝树66小区二次改造    add   llh  20170717   end   */

/**
 * 第三方绑定确认
 * @param req
 * @param res
 */
exports.thirdPartyBind = function (req, res) {
    var input = req.body;

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    appService.thirdPartyBindService(input, clientIp, function (err, result) { // 新
    // appService.thirdPartyBindService(input, function (err, result) { // 旧
        if (err) {
            logger.error('Failed to' +
                ' thirdPartyBind ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2007))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result[2], 2007));

            var clickMessage = {
                type: 52,
                typeDesc: '第三方绑定手机号',
                deviceId: req.params.deviceId,
                vname: req.query.vname,
                vcode: req.query.vcode,
                os: req.query.type,
                createTime: new Date().getTime()
            };
            toolUtil.putMessageLogMQ(clickMessage);
        }
    })
};

/**
 * 第三方登陆
 * @param req
 * @param res
 */
exports.thirdPartyLogin = function (req, res) {
    var id = req.body.id;
    var lang = req.cparams.lang;

    console.log('id = ', id);

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    appService.thirdPartyLoginService(id, clientIp, function (err, result) { // 新
    // appService.thirdPartyLoginService(id, function (err, result) { // 旧
        if (err) {
            logger.error('Failed to thirdPartyLogin ---' + err.message);

            var msg = {message: (lang && lang == 'en_US') ? err.message_en_US : err.message};
            res.json(messageUtil.composeErrorMessage(req, msg, 2008))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2008));

            if (result.isRegister === false) {
                var clickMessage = {
                    type: 51,
                    typeDesc: '第三方登陆（第一次登陆）',
                    deviceId: req.params.deviceId,
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(clickMessage);
            }
        }
    })
};

/**
 * 获取开通城市列表
 * @param req
 * @param res
 */
exports.getCityList = function (req, res) {
    var lat = req.params.lat;
    var lng = req.params.lng;
    var token = req.params.token;

    lat = Number(lat) + '';
    lng = Number(lng) + '';

    appService.getCityListService(lat, lng, token, function (err, result) {
        if (err) {
            logger.error('Failed to getCityList ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2009))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2009));
        }
    });
};

exports.getHotCityList = function (req, res) {
    var lat = req.params.lat;
    var lng = req.params.lng;
    var token = req.params.token;

    var lang = req.cparams.lang;

    lat = Number(lat) + '';
    lng = Number(lng) + '';

    appService.getHotCityListService(lat, lng, token, function (err, result) {
        if (err) {
            logger.error('Failed to getCityList ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2021))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2021));
        }
    })
};


/**
 * 获取小区列表
 * @param req
 * @param res
 */
exports.getCommunityList = function (req, res) {
    var lat = req.params.lat;
    var lng = req.params.lng;
    var cityId = req.params.cityId;
    var page = req.params.page;
    var token = req.params.token;

    var lang = req.cparams.lang;

    lat = Number(lat) + '';
    lng = Number(lng) + '';

    appService.getCommunityListService(lat, lng, cityId, page, token, function (err, result) {
        if (err) {
            logger.error('Failed to getCommunityListService ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2010))
        } else {
            if (lang && lang == 'en_US') {
                result.map(function (c) {

                    // if (!c._doc.pinyin)
                    // c._doc.pinyin = pinyin(c._doc.communityName, {style: pinyin.STYLE_NORMAL})
                    //     .map(function (b) {
                    //         b = b.map(function (a) {
                    //             a = a.substring(0, 1).toUpperCase() + a.substring(1);
                    //             return a;
                    //         })
                    //
                    //         return b
                    //     })
                    //     .join(' ');
                    //
                    // c._doc.communityName = c._doc.pinyin;
                    c._doc.communityName = c._doc.communityName_en_US;
                    // c._doc.communityName = c._doc.pinyin.toUpperCase();
                    // c.pinyin = undefined;
                    // console.log(typeof(c._doc.pinyin));
                    // console.log(c);
                })
            }

            res.json(messageUtil.composeSucceededMessage(req, null, {communityList: result}, 2010));
        }
    })
};


/**
 * 搜索小区
 * @param req
 * @param res
 */
exports.searchCommunity = function (req, res) {
    var lat = req.params.lat;
    var lng = req.params.lng;
    var cityId = req.params.cityId;
    var keyword = req.params.keyword;
    var token = req.params.token;

    var lang = req.cparams.lang;

    lat = Number(lat) + '';
    lng = Number(lng) + '';

    keyword = (lang && lang == 'en_US') ?
        {pinyin: new RegExp(keyword.replace(/ /g, '').toLowerCase())} : {communityName: new RegExp(keyword)};

    appService.searchCommunityService(lat, lng, cityId, keyword, token, function (err, result) {
        if (err) {
            logger.error('Failed to searchCommunity ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2011))
        } else {
            if (lang && lang == 'en_US') {
                result.map(function (c) {
                    // console.log(c);
                    // if (!c._doc.pinyin)
                    //     c._doc.pinyin = pinyin(c._doc.communityName, {style: pinyin.STYLE_NORMAL}).join('');


                    // c._doc.communityName = c._doc.pinyin.toUpperCase();
                    c._doc.communityName = c._doc.communityName_en_US;
                    delete c.pinyin;
                    delete c.communityName;
                })
            }

            res.json(messageUtil.composeSucceededMessage(req, null, {communityList: result}, 2011));
        }
    })
};


/**
 * 获取V认证类型
 * @param req
 * @param res
 */
exports.getVerifiedType = function (req, res) {
    var token = req.params.token;

    var list = [
        {
            type: 0,
            value: '住户'
        }, {
            type: 2,
            value: '物业'
        }
    ];

    res.json(messageUtil.composeSucceededMessage(req, null, list, 2012))
};


/**
 * v认证提交单元号、房号信息
 * @param req
 * @param res
 */
exports.postVerifiedProfile = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    appService.postVerifiedProfileService(token, input, function (err, result) {
        if (err) {
            logger.error('Failed to postVerifiedProfile ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2013))
        } else {
            var data = {
                roomUnit: input.roomUnit,
                roomNumber: input.roomNumber
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 2013));
        }
    })
};

/**
 * 定位认证
 * @param req
 * @param res
 */
exports.locationVerified = function (req, res) {
    var token = req.params.token;
    var communityId = req.body.communityId;
    var lat = req.body.lat;
    var lng = req.body.lng;

    appService.locationVerifiedService(token, communityId, lat, lng, function (err, result) {
        if (err) {
            logger.error('Failed to locationVerified ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2014))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result[4], 2014));

            appService.sendVerifiedSuccessfulRewardsService(token);
        }
    })
};

exports.getMyInvitationPartRecord = function (req, res) {
    var token = req.params.token;

    appService.getMyInvitationPartRecordService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getMyInvitationPartRecord ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2015))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2015));
        }
    })
};

exports.getMyInvitationRecord = function (req, res) {
    var token = req.params.token;
    var page = req.params.page;

    appService.getMyInvitationRecordService(token, page, function (err, result) {
        if (err) {
            logger.error('Failed to getMyInvitationRecord ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2016))
        } else {
            var data = {
                records: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 2016));
        }
    })
};


/**
 * 我的邀请奖励数值
 * @param req
 * @param res
 */
exports.getMyInvitationCount = function (req, res) {
    var token = req.params.token;

    appService.getMyInvitationCountService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getMyInvitationCount ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2017))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2017));
        }
    })
};

/**
 * 邀请排行榜
 * @param req
 * @param res
 */
exports.getMyInvitationRank = function (req, res) {
    var token = req.params.token;
    var vcode = req.query.vcode;
    var clickSource = req.query.clickSource;

    appService.getMyInvitationRankService(token, vcode, function (err, result) {
        if (err) {
            logger.error('Failed to getMyInvitationRank ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2018))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2018));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    type: 43,
                    clickSource: clickSource,
                    typeDesc: '邀请有礼',
                    deviceId: req.params.deviceId,
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.userSignIn = function (req, res) {
    var token = req.params.token;

    appService.userSignInService(token, function (err, result) {
        if (err) {
            logger.error('Failed to userSignIn ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1018))
        } else {
            /*  宝宝树66小区二次改造    mod   chenf  20170815   start   */
            var data = {
                signInMsg: result.signInMsg,
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   start   */
                url:result.url,
                isLuckDraw : result.isLuckDraw ? true : false
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   end   */
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1018));
           /* var dateList = [];

            for (i = 0; i < 7; i++) {

                var date = moment(result.start, 'YYYYMMDD').add(i, 'day');
                var temp = {
                    date: date.format('M.D'),
                    score: i + 1,
                    isSignIn: Number(result.now) >= Number(date.format('YYYYMMDD'))
                };
                dateList.push(temp);
            }

            var data = {
                signInMsg: result.signInMsg,
                dateList: dateList
            };


            scoreProxy.invoke('getScoreInfoByUid', [token], function (err, value) {
                if (err) {
                    logger.error('Exception happened when getUserScore ...!');
                    res.json(messageUtil.composeFailedMessage(req, '获取情值失败', 1018));
                } else {
                    var score = JSON.parse(decodeURIComponent(value));
                    if (score.status != 0) {
                        logger.error('getUserScore----' + score.msg);
                        res.json(messageUtil.composeFailedMessage(req, score.msg, 1018));
                    } else {

                        data.currentValue = score.data.scoreInfo.currentValue;
                        res.json(messageUtil.composeSucceededMessage(req, null, data, 1018))
                    }
                }
            });*/

            var message = {
                userId: token,
                type: 11,
                typeDesc: '签到',
                deviceId: req.params.deviceId,
                vname: req.query.vname,
                vcode: req.query.vcode,
                os: req.query.type,
                createTime: new Date().getTime()
            };
            toolUtil.putMessageLogMQ(message);
            /*  宝宝树66小区二次改造    mod   chenf  20170815   end   */
        }
    })
};

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   start   */
exports.userLuckDrawSuccess = function (req, res) {
    var token = req.params.token;

    appService.userLuckDrawSuccess(token, function (err, result) {
        if (err) {
            logger.error('Failed to userLuckDraw ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1018))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1018));
        }
    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   end   */

exports.downloadMarketZip = function (req, res) {
    var appV = req.params.version;

    if (appV == 'v7') appV = 'v0';
    var path = '/mnt/market/zip/' + appV + '_' + MARKET_VERSION + '.zip';
    res.download(path)
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 角色申请
 * @param req
 * @param res
 */
exports.applyUserRole = function (req, res) {

    var token = req.params.token;
    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to applyUserRole - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to applyUserRole - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to applyUserRole - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to applyUserRole! - " + gagOrNot);

                /*  宝宝树66小区五期   mod  小区大使申请 guo.xiaomin  20171121   start   */
                var input = req.body;
                var realName = input.realName; // 真实姓名
                var wxName = input.wxName; // 微信号
                var name = input.name;
                if(!realName || !wxName) {
                    logger.debug("小区大使没有姓名或微信号..." + name);
                    appService.applyUserRoleService(token, input, function (err, result) {
                        if (err) {
                            logger.error('Failed to applyUserRoleService ---' + err.message);
                            res.json(messageUtil.composeErrorMessage(req, err, 2019))
                        } else {
                            logger.debug("小区大使申请提交成功..." + name);
                            res.json(messageUtil.composeSucceededMessage(req, null, null, 2019));
                        }
                    })
                } else {
                    if(realName.length > 32 || wxName.length > 20) {
                        logger.debug("姓名或微信号长度太长..." + name);
                        res.json(messageUtil.composeErrorMessage(req, {status : 0, message: "姓名和微信号长度太长!"}, 2019));
                    } else {
                        appService.applyUserRoleService(token, input, function (err, result) {
                            if (err) {
                                logger.error('Failed to applyUserRoleService ---' + err.message);
                                res.json(messageUtil.composeErrorMessage(req, err, 2019))
                            } else {
                                logger.debug("小区大使申请提交成功..." + name);
                                res.json(messageUtil.composeSucceededMessage(req, null, null, 2019));
                            }
                        })
                    }
                }
                /*  宝宝树66小区五期   mod  小区大使申请 guo.xiaomin  20171121   end   */

            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * 角色查询
 * @param req
 * @param res
 */
exports.getUserRoleService = function (req, res) {

    var token = req.params.token;
    var type = req.params.type;

    appService.getUserRoleService(token, type, function (err, result) {
        if (err) {
            logger.error('Failed to applyUserRoleService ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 2020))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2020));
        }
    })
};

exports.contactsInvite = function (req, res) {
    var input = req.body;

    appService.contactsInviteService(input, function (err, result) {
        if (err) {
            logger.error('Failed to postUserContacts...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 2022));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2022));
        }
    })
};

exports.getSplashScreen = function (req, res) {

    appService.getSplashScreenService(function (err, result) {
        if (err) {
            logger.error('Failed to postUserContacts...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 2023));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2023));
        }
    })
};

exports.getCommunityFounder = function (req, res) {
    var token = req.query.token;

    appService.getCommunityFounderService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getCommunityFounder...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 2024));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2024));
        }
    })
};

/* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 start */
/**
 * 校验最新用户协议版本
 */
exports.checkProtocolVersion = function (req, res) {
    // 取得用户手机号
    var mobilePhone = req.body.mobilePhone;

    appService.checkProtocolVersionService(mobilePhone, function (err, result) {
        if (err) {
            logger.error('Failed to checkProtocolVersion...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, {status: 0}, 2025))
        } else {
            logger.debug('Succeed to checkProtocolVersion...!' + result);
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2025));
        }
    });
};
/* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 end */